# 同步代码到远程服务器并编译
# 用法: .\sync-and-build.ps1 [clean]

# 配置
$REMOTE_SERVER = "root@192.168.50.160"
$REMOTE_PROJECT_PATH = "/home/chenhg/gitee/xsan"
$LOCAL_PROJECT_PATH = "."  # 当前目录
$BUILD_LOG = "/tmp/build.log"

# 检查是否需要清理构建
$clean = $false
if ($args.Count -gt 0 -and $args[0] -eq "clean") {
    $clean = $true
    Write-Host "将执行清理构建" -ForegroundColor Yellow
}

# 同步代码到服务器
Write-Host "正在同步代码到远程服务器..." -ForegroundColor Green
$excludeFile = "$env:TEMP\rsync-exclude.txt"
@(
    ".git/"
    "build/"
    "*.o"
    "*.so"
    "*.a"
) | Out-File -FilePath $excludeFile -Encoding ascii

# 使用scp递归复制文件（Windows PowerShell中没有rsync）
ssh $REMOTE_SERVER "mkdir -p $REMOTE_PROJECT_PATH"
scp -r "$LOCAL_PROJECT_PATH\*" "${REMOTE_SERVER}:$REMOTE_PROJECT_PATH/"

# 在服务器上执行构建
Write-Host "正在远程服务器上执行构建..." -ForegroundColor Green
if ($clean) {
    ssh $REMOTE_SERVER "cd $REMOTE_PROJECT_PATH; rm -rf build; mkdir -p build; cd build; cmake ..; make -j4 > $BUILD_LOG 2>&1"
} else {
    ssh $REMOTE_SERVER "cd $REMOTE_PROJECT_PATH; mkdir -p build; cd build; cmake ..; make -j4 > $BUILD_LOG 2>&1"
}

# 检查构建结果
$buildExitCode = ssh $REMOTE_SERVER "echo $?"
if ($buildExitCode -eq "0") {
    Write-Host "构建成功完成!" -ForegroundColor Green
} else {
    Write-Host "构建失败，查看错误信息:" -ForegroundColor Red
    ssh $REMOTE_SERVER "cat $BUILD_LOG | grep -A 5 error:"
    Write-Host "要查看完整的构建日志，请运行: ssh $REMOTE_SERVER 'cat $BUILD_LOG'" -ForegroundColor Yellow
}

Write-Host "同步并构建完成。" -ForegroundColor Green 